package com.kkd.kkdapp.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.HeadGridViewAdapter;
import com.kkd.kkdapp.adapter.HeadGridViewAdapter.GridViewItemListener;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.HeadListData;
import com.kkd.kkdapp.http.entity.ImageTips;
import com.kkd.kkdapp.http.entity.MyHead;
import com.kkd.kkdapp.http.entity.NewMisTips;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.FileUtils;
import com.kkd.kkdapp.utils.ImageUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.UIEmptyHandleUtil;
import com.kkd.kkdapp.view.KKdDialog;
import com.kkd.kkdapp.view.MyGridView;
import com.kkd.kkdapp.view.RoundImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MyHeadPortraitActivity extends BaseActivity implements
		OnClickListener {

	private static final int UPDATEHEAD_OK = 1;
	private static final int UPDATEHEAD_NO = 2;
	private static final int HEADLIST_OK = 3;
	private static final int HEADLIST_NO = 8;
	private static final int HEADEXCHANGE_OK = 4;
	private static final int HEADEXCHANGE_NO = 5;
	private static final int HEADPRODUCTSET_OK = 6;
	private static final int HEADPRODUCTSET_NO = 7;
	private RelativeLayout top_img; // 返回
	private RoundImageView head; // 头像
	private TextView dimis;
	private KKdDialog ppw;
	private String filePath;
	private String urserHeadUrl;
	private String desc;
	private RelativeLayout newbie_task_rl; // 　新手任务提示
	private List<MyHead> arr = new ArrayList<MyHead>();
	private MyGridView mGridView;
	private HeadGridViewAdapter adapter;
	private TextView newbie_task_tv1; // 新手任务提示语1
	private TextView newbie_task_tv2; // 新手任务提示语2
	private TextView newbie_task_tv3, newbie_task_tv4, newbie_task_tv5; // 新手任务提示语3
	private Dialog toLoadDialog; // 等待Dialog
	private Dialog mDialog;
	private int mPosition = -1;
	private LinearLayout nonEmpty_ll;
	private RelativeLayout null_rl;
	private ImageView img_null;
	private TextView tv_null;
	private int statusCode;

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UPDATEHEAD_OK:
				mDialog.dismiss();
				mDialog.cancel();
				mDialog = null;
				showToast("保存成功");
				AppUtil.makeToastForCustomer(MyHeadPortraitActivity.this,
						"保存成功");
				ImageLoader.getInstance().displayImage(urserHeadUrl, head);
				break;
			case UPDATEHEAD_NO:
				mDialog.dismiss();
				mDialog.cancel();
				mDialog = null;
				if (statusCode == KkdHttpClient.NO_NET) {
					showToast("网络错误，请稍后重试");
				} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
					showToast("服务异常，请稍后重试");
				}
				break;
			case HEADLIST_OK:
				UIEmptyHandleUtil.uiNullDispose(false, nonEmpty_ll, null_rl,
						img_null, tv_null, "", 0);
				HeadListData data = (HeadListData) msg.obj;
				arr.clear();
				arr.addAll(data.getDataList());
				adapter.notifyDataSetChanged();
				ImageTips imageTips = data.getImageTips();
				newbie_task_tv1.setText(imageTips.getImageTips1());
				newbie_task_tv1.getPaint().setFakeBoldText(true);
				newbie_task_tv2.setText(imageTips.getImageTips2());
				newbie_task_tv2.getPaint().setFakeBoldText(true);

				// 新手任务提示语
				NewMisTips newMisTips = data.getNewMisTips();
				String sNewMisTips = newMisTips.getNewMisTips();
				maxTime = (int) (newMisTips.getTimeSpace() / 1000);
				if (TextUtils.isEmpty(sNewMisTips)) {
					newbie_task_rl.setVisibility(View.GONE);
				} else {
					newbie_task_rl.setVisibility(View.VISIBLE);
				}
				if (!TextUtils.isEmpty(sNewMisTips) && maxTime > 0) {
					updateNewTaskSpaceTime();
					startTime();
				}
				break;
			case HEADLIST_NO:
				if (statusCode == KkdHttpClient.NO_NET) {
					UIEmptyHandleUtil.uiNullDispose(true, nonEmpty_ll, null_rl,
							img_null, tv_null, "网络错误，请稍后重试",
							R.drawable.img_null_net);
				} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
					UIEmptyHandleUtil.uiNullDispose(true, nonEmpty_ll, null_rl,
							img_null, tv_null, "服务异常，请稍后重试",
							R.drawable.img_null_net);
				}
				break;
			case HEADEXCHANGE_OK:
				showToast("兑换成功");
				closeToLoadDialog();
				arr.get(mPosition).setStatus(2);
				adapter.notifyDataSetChanged();
				break;
			case HEADEXCHANGE_NO:
				desc = (String) msg.obj;
				showToast(desc);
				closeToLoadDialog();
				break;
			case HEADPRODUCTSET_OK:
				String imageUrl = (String) msg.obj;
				ImageLoader.getInstance().displayImage(imageUrl, head);
				PreferenceUtils.getInstance().setHeadUrl(
						MyHeadPortraitActivity.this, imageUrl);
				for (int i = 0; i < arr.size(); i++) {
					if (arr.get(i).getStatus() == 1) {
						arr.get(i).setStatus(2);
					}
				}
				arr.get(mPosition).setStatus(1);
				adapter.notifyDataSetChanged();
				showToast("设置成功");
				// closeToLoadDialog();
				break;
			case HEADPRODUCTSET_NO:
				desc = (String) msg.obj;
				showToast(desc);
				// closeToLoadDialog();
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_head_portrait);
		mTintManager.setStatusBarTintResource(0x00000000);
		initView();
		setListener();
		headList();
	}

	/**********
	 * 初始化控件
	 **********/
	public void initView() {
		top_img = (RelativeLayout) this.findViewById(R.id.top_img);
		head = (RoundImageView) this.findViewById(R.id.head);
		newbie_task_rl = (RelativeLayout) this
				.findViewById(R.id.newbie_task_rl);
		newbie_task_tv1 = (TextView) this.findViewById(R.id.newbie_task_tv1);
		newbie_task_tv2 = (TextView) this.findViewById(R.id.newbie_task_tv2);
		newbie_task_tv3 = (TextView) this.findViewById(R.id.newbie_task_tv3);
		newbie_task_tv4 = (TextView) this.findViewById(R.id.newbie_task_tv4);
		newbie_task_tv5 = (TextView) this.findViewById(R.id.newbie_task_tv5);
		nonEmpty_ll = (LinearLayout) this.findViewById(R.id.nonEmpty_ll);
		null_rl = (RelativeLayout) this.findViewById(R.id.null_rl);
		img_null = (ImageView) this.findViewById(R.id.img_null);
		tv_null = (TextView) this.findViewById(R.id.tv_null);

		mGridView = (MyGridView) this.findViewById(R.id.gridview);
		mGridView.setFocusable(false);
		adapter = new HeadGridViewAdapter(this, arr);
		mGridView.setAdapter(adapter);
		View view_top = this.findViewById(R.id.view_top);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
			view_top.setVisibility(View.GONE);
		}
	}

	/**************
	 * 注册监听事件
	 **************/
	public void setListener() {
		top_img.setOnClickListener(this);
		head.setOnClickListener(this);
		adapter.setGridViewItemListenerr(new GridViewItemListener() {

			@Override
			public void posion(int posion, String text) {
				if (!TextUtils.isEmpty(text)) {
					if ("兑换".equals(text)) {
						if (arr.size() > 0) {
							mPosition = posion;
							headExchange(arr.get(posion).getCoinCount(), arr
									.get(posion).getImageCode());
						}
					} else if ("设为头像".equals(text)) {
						if (arr.size() > 0) {
							mPosition = posion;
							headProductSet(arr.get(posion).getImageCode());
						}
					}
				}
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		ImageLoader.getInstance().displayImage(
				PreferenceUtils.getInstance().getHeadUrl(
						MyHeadPortraitActivity.this), head);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_img: // 返回
			finish();
			break;
		case R.id.head: // 设置头像
			SystemUtils.onEvent("Account_Sett_Personal_Head", 1);
			showPopupWindow(v);
			break;

		}

	}

	/**************
	 * 设置头像对话框
	 * 
	 *************/
	public void showPopupWindow(View v) {
		LayoutInflater linflater = LayoutInflater.from(this);
		View view = linflater.inflate(R.layout.popupwindow, null);
		dimis = (TextView) view.findViewById(R.id.dimis);
		RelativeLayout dimiss_rl = (RelativeLayout) view
				.findViewById(R.id.dimiss_rl);
		dimiss_rl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ppw.isShowing()) {
					ppw.dismiss();
				}
			}
		});
		TextView photograph = (TextView) view.findViewById(R.id.photograph);
		photograph.setOnClickListener(new OnClickListener() { // 拍照

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);

						filePath = FileUtils.getKKDHeadIconPath()
								+ System.currentTimeMillis() + ".png";
						intent.putExtra(MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(new File(filePath)));
						PreferenceUtils.putString("headicon", filePath,
								MyHeadPortraitActivity.this);
						startActivityForResult(intent,
								ImageUtils.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

						ppw.dismiss();// 关闭弹出框
					}
				});
		TextView photo = (TextView) view.findViewById(R.id.photo);
		photo.setOnClickListener(new OnClickListener() { // 相册

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						ImageUtils.IMAGE_UNSPECIFIED);
				startActivityForResult(intent, ImageUtils.PHOTO_ZOOM);

				ppw.dismiss();// 关闭弹出框
			}
		});
		dimis.setOnClickListener(new OnClickListener() { // 取消

			@Override
			public void onClick(View v) {
				if (ppw.isShowing()) {
					ppw.dismiss();
				}
			}
		});
		ppw = new KKdDialog(this, R.style.TransparentDialog);
		ppw.setContentView(view);
		ppw.setCanceledOnTouchOutside(true);
		// ppw = new PopupWindow(view, LayoutParams.MATCH_PARENT,
		// LayoutParams.MATCH_PARENT, true);
		// ppw.setOutsideTouchable(true);
		// ppw.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		if (ppw.isShowing()) {
			ppw.dismiss();
		} else {
			ppw.show();
			// ppw.showAtLocation(v, Gravity.CENTER, 0, 0);
		}
	}

	/**
	 * 收缩图片
	 * 
	 * @param uri
	 */
	private String zoomfilePath;

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");

		zoomfilePath = FileUtils.getKKDHeadIconPath()
				+ System.currentTimeMillis() + ".png";
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(zoomfilePath)));
		PreferenceUtils.putString("zoomfilePath", zoomfilePath,
				MyHeadPortraitActivity.this);

		intent.setDataAndType(uri, ImageUtils.IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, ImageUtils.PHOTO_RESOULT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 拍照
		if (requestCode == ImageUtils.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			// 设置文件保存路径
			if (TextUtils.isEmpty(filePath))
				filePath = PreferenceUtils.getString("headicon", "",
						MyHeadPortraitActivity.this);
			;
			File picture = new File(filePath);
			if (picture != null) {
				if (picture.exists()) {
					startPhotoZoom(Uri.fromFile(picture));
				} else {
				}
			}
		} else if (requestCode == ImageUtils.PHOTO_ZOOM) {
			if (data != null) {
				startPhotoZoom(data.getData());
				LogUtil.e("uri", data.getData().toString());
			}
		}
		if (data == null)
			return;
		// 图片处理结果
		if (requestCode == ImageUtils.PHOTO_RESOULT) {
			pictureResult();
		}
	}

	/************************
	 * 图片处理结果
	 ************************/
	public void pictureResult() {
		if (TextUtils.isEmpty(zoomfilePath))
			zoomfilePath = PreferenceUtils.getString("zoomfilePath", "",
					MyHeadPortraitActivity.this);
		;
		File picture = new File(zoomfilePath);
		if (picture != null) {
			if (picture.exists()) {
				Bitmap bitmap = BitmapFactory.decodeFile(zoomfilePath);// 获取相机返回的数据，并转换为Bitmap图片格式
				if (bitmap != null) {
					String img = ImageUtils.bitmaptoString(bitmap);
					LogUtil.e("img", img);
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// 把数据写入文件
					if (mDialog == null)
						mDialog = DialogUtils.toLoadDialog(this, "正在保存...");
					KkdHttpMagager.getInstance().getPhtotoUploadManager(img,
							String.class, new HttpCallBack() {

								@Override
								public void onSuccess(int statusCode,
										Object responseBody) {
									try {
										String responseString = responseBody
												.toString();
										Log.e("response", responseString);
										JSONObject data = new JSONObject(
												responseString);
										LogUtil.e("userHeadUrl",
												data.getString("userHeadUrl"));
										urserHeadUrl = data
												.getString("userHeadUrl");
										PreferenceUtils
												.getInstance()
												.setMyproperty(
														MyHeadPortraitActivity.this,
														"");
										PreferenceUtils
												.getInstance()
												.setEarnings(
														MyHeadPortraitActivity.this,
														"");
										PreferenceUtils
												.getInstance()
												.setHeadUrl(
														MyHeadPortraitActivity.this,
														data.getString("userHeadUrl"));
										mHandler.sendEmptyMessage(UPDATEHEAD_OK);
									} catch (JSONException e) {
										e.printStackTrace();
									}

								}

								@Override
								public void onFailure(int statusCode,
										String desc) {
									MyHeadPortraitActivity.this.statusCode = statusCode;
									MyHeadPortraitActivity.this.desc = desc;
									mHandler.sendEmptyMessage(UPDATEHEAD_NO);
								}
							});
				}
			}
		}

	}

	/************
	 * 头像列表接口
	 ************/
	public void headList() {
		KkdHttpMagager.getInstance().headList(HeadListData.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						HeadListData data = (HeadListData) responseBody;
						Message msg = new Message();
						msg.what = HEADLIST_OK;
						msg.obj = data;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						MyHeadPortraitActivity.this.statusCode = statusCode;
						Message msg = new Message();
						msg.obj = desc;
						msg.what = HEADLIST_NO;
						mHandler.sendMessage(msg);
					}
				});
	}

	/********
	 * 快乐币兑换头像接口
	 ********/
	public void headExchange(int coinCount, String imageCode) {
		showToLoadDialog("兑换中，请稍候...");
		KkdHttpMagager.getInstance().headExchange(coinCount, imageCode,
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mHandler.sendEmptyMessage(HEADEXCHANGE_OK);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.obj = desc;
						msg.what = HEADEXCHANGE_NO;
						mHandler.sendMessage(msg);
					}
				});
	}

	/*************
	 * 
	 * 产品头像设置
	 * 
	 *************/
	public void headProductSet(String imageCode) {
		// showToLoadDialog("正在设置...");
		KkdHttpMagager.getInstance().headProductSet(imageCode, String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						String imageUrl = responseBody.toString();
						LogUtil.e("data", imageUrl);
						Message msg = new Message();
						msg.obj = imageUrl;
						msg.what = HEADPRODUCTSET_OK;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.obj = desc;
						msg.what = HEADPRODUCTSET_NO;
						mHandler.sendMessage(msg);

					}
				});
	}

	public int maxTime = 86400;
	private int mRecordTime = 0;
	private boolean isRecoding = false;
	public static final int RECORD_TIMER = 8112;
	public static final int RECORD_DONE = 8113;
	public static final int RECORD_ERROR = 8114;
	public static final int PERIOD = 1000;
	private TimerTask mTimerTask_newTask = null;
	private Timer mTimer;
	public TimerHandler mTimerHandler = new TimerHandler(this);
	WeakReference<MyHeadPortraitActivity> reference;

	public void updateNewTaskSpaceTime() {
		int dtime = (int) (maxTime - mRecordTime);
		int ss = dtime % 60;
		int mm = (dtime / 60) % 60;
		int hh = dtime / 60 / 60;
		String tip_time_newtask = "";
		if (hh < 1) { // 不足一小时
			tip_time_newtask = mm + "分" + ss + "秒后";
		} else if (hh >= 1 && hh < 24) { // 小于一天大于1小时
			tip_time_newtask = "今天24时后";
		} else if (hh >= 24) { // 大于一天
			tip_time_newtask = hh / 24 + "天后";
		}
		newbie_task_tv3.setText("新手任务将在");
		newbie_task_tv4.setText(tip_time_newtask);
		newbie_task_tv5.setText("结束");
	}

	public void onTimerFinish() {
		headList();
	}

	public void startTime() {
		mRecordTime = 0;
		if (!isRecoding) {
			if (mTimerTask_newTask != null) {
				mTimerTask_newTask.cancel();
				mTimerTask_newTask = null;
			}
			if (mTimer != null) {
				mTimer.cancel();
				mTimer = null;
			}
			mTimerTask_newTask = new RecordTimeTask();
			mTimer = new Timer();
			mTimer.schedule(mTimerTask_newTask, 0, PERIOD);
		}

		isRecoding = true;

	}

	private class RecordTimeTask extends TimerTask {
		@Override
		public void run() {
			if (isRecoding) {
				mRecordTime++;
				if (mRecordTime <= maxTime) {
					Message message = new Message();
					message.what = RECORD_TIMER;
					message.obj = mRecordTime;
					mTimerHandler.sendMessage(message);
				} else {
					Message message = new Message();
					message.what = RECORD_DONE;
					message.arg1 = mRecordTime;
					message.obj = "";
					mTimerHandler.sendMessage(message);
					isRecoding = false;
				}
			}

		}
	}

	public class TimerHandler extends Handler {

		public TimerHandler(MyHeadPortraitActivity activity) {
			reference = new WeakReference<MyHeadPortraitActivity>(activity);
		}

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case RECORD_TIMER:
				if (reference != null && reference.get() != null)
					reference.get().updateNewTaskSpaceTime();
				break;
			case RECORD_DONE:
				if (reference != null && reference.get() != null) {
					reference.get().onTimerFinish();
					if (mTimer != null) {
						mTimer.cancel();
						mTimer = null;
					}
					if (mTimerTask_newTask != null) {
						mTimerTask_newTask.cancel();
						mTimerTask_newTask = null;
					}
					reference.clear();
					reference = null;
				}
				break;
			default:
				break;
			}
		}
	}

	// 等待Dialog
	public void showToLoadDialog(String content) {
		if (toLoadDialog != null) {
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
		toLoadDialog = DialogUtils.toLoadDialog(this, content);
		toLoadDialog.show();
	}

	// 等待Dialog
	public void closeToLoadDialog() {
		if (toLoadDialog != null) {
			toLoadDialog.dismiss();
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask_newTask != null) {
			mTimerTask_newTask.cancel();
			mTimerTask_newTask = null;
		}
		if (reference != null && reference.get() != null) {
			reference.clear();
			reference = null;
		}
		if (ppw != null) {
			ppw.cancel();
			ppw = null;
		}
		closeToLoadDialog();
	}

}
